package com.google.demo.Activity;

import java.util.Observable;
import java.util.Observer;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View;
import android.widget.ScrollView;

import com.google.demo.Config;
import com.google.demo.R;
import com.google.demo.ScanQRCodeApp;
import com.google.demo.Data.Controler.DataHelper;
import com.google.demo.GPS.MyLocationManager;
import com.google.demo.Util.Prefs;
import com.google.demo.Util.Util;
import com.google.demo.interfaces.AlertDialogInterface;
import com.google.demo.interfaces.ScanningGPS;
import com.google.demo.model.DataResult;
import com.google.demo.model.InputData;
import com.google.demo.view.AnimValidation;

public class InputDataActivity extends MainActivity  implements Observer {
	private MyLocationManager mLocationManager;
	private InputDataActivity _me = this;
	private String mQRCode = "";
	private LayoutInflater mLayoutInflater;
	private ScrollView mInputDataLayout;
	private EditText mEditTextSalesOfPhonesThisMonth;
	private EditText mEditTextSalesOfSimsThisMonth;
	private EditText mEditTextSalesOfCardsThisMonth;

	private TextView mTextViewSalesOfPhonesThisMonth;
	private TextView mTextViewSalesOfSimsThisMonth;
	private TextView mTextViewSalesOfCardsThisMonth;
	
	private LinearLayout mScanCodeErrorLayout;
	private Button mBtnRescan;
	private Button mBtnDone;
	String mLat = "200", mLon = "0";
	
	private boolean mIsFirstOpenGPS = false;
	private boolean mIsScanQRCodeOut = false;
	private ProgressDialog _waitingDialog;
	
	private Thread thread;
	private Handler handler=new Handler();
	
	private void initControls(){
		getTextViewHeader().setText(getString(R.string.scan_code));
		getmButton_left().setVisibility(View.GONE);
		getmButton_right().setVisibility(View.GONE);
		getLeft_view().setVisibility(View.GONE);
		getRight_view().setVisibility(View.GONE);
		mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mInputDataLayout = (ScrollView) mLayoutInflater.inflate(R.layout.inputdata_layout, null);
		mEditTextSalesOfPhonesThisMonth = (EditText)  mInputDataLayout.findViewById(R.id.etv_salesOfPhonesThisMonth);
		mEditTextSalesOfSimsThisMonth = (EditText)  mInputDataLayout.findViewById(R.id.etv_salesOfSimsThisMonth);
		mEditTextSalesOfCardsThisMonth = (EditText)  mInputDataLayout.findViewById(R.id.etv_salesOfCardsThisMonth);
		
		mTextViewSalesOfPhonesThisMonth=(TextView) mInputDataLayout.findViewById(R.id.txtv_salesOfPhonesThisMonth);
		mTextViewSalesOfSimsThisMonth=(TextView) mInputDataLayout.findViewById(R.id.txtv_salesOfSimsThisMonth);
		mTextViewSalesOfCardsThisMonth=(TextView) mInputDataLayout.findViewById(R.id.txtv_salesOfCardsThisMonth);
		
		AnimValidation validation=new AnimValidation(_me, 1, mEditTextSalesOfPhonesThisMonth, 
				mEditTextSalesOfSimsThisMonth, mEditTextSalesOfCardsThisMonth, 
				mTextViewSalesOfPhonesThisMonth, mTextViewSalesOfSimsThisMonth, 
				mTextViewSalesOfCardsThisMonth);
		validation.validAnim();
		
		mBtnDone = (Button) mInputDataLayout.findViewById(R.id.button_done);
		mBtnDone.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onClickButtonDone();
			}
		});
		
		mScanCodeErrorLayout = (LinearLayout) mLayoutInflater.inflate(R.layout.scan_error_layout, null);
		mBtnRescan = (Button) mScanCodeErrorLayout.findViewById(R.id.btn_rescan);
		mBtnRescan.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mScanCodeErrorLayout.setVisibility(View.GONE);
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
				startActivityForResult(intent, com.google.demo.Config.QR_CODE_ACTIVITY_REQUEST_CODE);
			}
		});
		
		getFrameLayoutMain().removeAllViews();
		getFrameLayoutMain().addView(mScanCodeErrorLayout);
		mScanCodeErrorLayout.setVisibility(View.GONE);
		mIsFirstOpenGPS = false;
	}
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ScanQRCodeApp app = ScanQRCodeApp.Instance();
		
		if(app.isLogin()){
			thread=new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Intent intent = new Intent("com.google.zxing.client.android.SCAN");
					intent.putExtra("SCAN_MODE", "QR_CODE_MODE");	
					startActivityForResult(intent,Config.QR_CODE_ACTIVITY_REQUEST_CODE);
					handler.post(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							initControls();
						}
					});
				}
			});
			thread.start();
		}else{
			Intent intent = new Intent(this,
					LoginMainActivity.class);				
			startActivity(intent);
			finish();
		}
		
		
		//Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		//intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
		//intent.putExtra("SCAN_MODE", "TWO_D_MODE");
		//intent.putExtra("SCAN_MODE", "ONE_D_MODE");
		//intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
		//startActivityForResult(intent,Config.QR_CODE_ACTIVITY_REQUEST_CODE) ;
	}
	
	private void onClickButtonDone()
	{
		InputData inputData = new InputData();
		inputData.setLat(mLat);
		inputData.setLon(mLon);
		inputData.setQRCode(mQRCode);
		if(mEditTextSalesOfPhonesThisMonth.getText().toString().equalsIgnoreCase("")){
			inputData.setSalesOfPhonesThisMonth(0);
		}else{
			inputData.setSalesOfPhonesThisMonth(Integer.parseInt(mEditTextSalesOfPhonesThisMonth.getText().toString()));
		}
		
		if(mEditTextSalesOfSimsThisMonth.getText().toString().equalsIgnoreCase("")){
			inputData.setSalesOfSimsThisMonth(0);
		}else{
			inputData.setSalesOfSimsThisMonth(Integer.parseInt(mEditTextSalesOfSimsThisMonth.getText().toString()));
		}
		
		if(mEditTextSalesOfCardsThisMonth.getText().toString().equalsIgnoreCase("")){
			inputData.setSalesOfCardsThisMonth(0);
		}else{
			inputData.setSalesOfCardsThisMonth(Integer.parseInt(mEditTextSalesOfCardsThisMonth.getText().toString()));
		}
		
		Bundle bundle = InputData.putInputDataToBundle(inputData);
		Intent intent = new Intent(_me, InputDataConfirmActivity.class);
		intent.putExtras(bundle);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == Config.QR_CODE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				if(Util.isNetworkAvailable())
				{
					String contents = data.getStringExtra("SCAN_RESULT");
					String format = data.getStringExtra("SCAN_RESULT_FORMAT");
					Log.e("Result_Scan", contents+","+format);
					if (contents.contains(getString(R.string.qrcode_valid_in))) {
						mLat = "200";
						mLon = "0";
						showProcessDialog();
						mQRCode = contents;
						if(mLocationManager == null)
						{
							mLocationManager = new MyLocationManager(this, scanningGPS);
						}
						mLocationManager.scanGPS();
					} else if(contents.contains(getString(R.string.qrcode_valid_out))) {
						mLat = "200";
						mLon = "0";
						mIsScanQRCodeOut = true;
						mQRCode = contents;
						showProcessDialog();
						if(mLocationManager == null)
						{
							mLocationManager = new MyLocationManager(this, scanningGPS);
						}
						mLocationManager.scanGPS();
					}
					else
					{
						mScanCodeErrorLayout.setVisibility(View.VISIBLE);
					}
				} else {
					Util.showError(InputDataActivity.this, getString(R.string.app_name), getString(R.string.NETWORK_ERROR));
					mScanCodeErrorLayout.setVisibility(View.VISIBLE);
				}
			} else {
				mScanCodeErrorLayout.setVisibility(View.VISIBLE);
			}
		}	
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(mIsFirstOpenGPS)
		{
			mLat = "200";
			mLon = "0";
			mIsFirstOpenGPS = false;
			mLocationManager.scanGPS();
		}
	}
	
	private ScanningGPS scanningGPS = new ScanningGPS() {

		@Override
		public void isFirstOpenGPS(boolean isFirstOpenGPS) {
			// TODO Auto-generated method stub
			mIsFirstOpenGPS = isFirstOpenGPS;
			if(isFirstOpenGPS == false)
			{
				mIsScanQRCodeOut = false;
				hideProcessDialog();
				mScanCodeErrorLayout.setVisibility(View.VISIBLE);
			}
				
		}
		
		@Override
		public void onScanGPS(boolean isSuccess, String result) {
			// TODO Auto-generated method stub
			if (isSuccess) {
				Prefs prefs = new Prefs(InputDataActivity.this);
				mLat = prefs.getStringValue("", Prefs.KEY_LAT_GPS);
				mLon = prefs.getStringValue("", Prefs.KEY_LON_GPS);
				if(mIsScanQRCodeOut == false) {
					
					Prefs pref = new Prefs(_me);
					String userName = pref.getStringValue("username", Config.USERNAME);
					DataHelper.getInstance().addObserver(_me);
					DataHelper.getInstance().postQRCodeIn(ScanQRCodeApp.Instance().getDeviceId(), userName, mLat, mLon, mQRCode, 0, 0, 0);
				} else {
					mIsScanQRCodeOut = false;
					Prefs pref = new Prefs(_me);
					String userName = pref.getStringValue("username", Config.USERNAME);
					DataHelper.getInstance().addObserver(_me);
					DataHelper.getInstance().postQRCodeOut(ScanQRCodeApp.Instance().getDeviceId(), userName, mLat, mLon, mQRCode, 0, 0, 0);
				}
			} else {
				hideProcessDialog();
				Util.showAlertDialog(InputDataActivity.this, mScanGPSCallback, true, true, getString(R.string.app_name), getString(R.string.scan_gps_error_message), getString(R.string.OK), getString(R.string.Cancel));
			}
		}

	};

	AlertDialogInterface mScanGPSCallback = new AlertDialogInterface() {
		
		@Override
		public void onChooseYesCallback() {
			// TODO Auto-generated method stub
			mLocationManager.scanGPS();
		}
		
		@Override
		public void onChooseNoCallback() {
			// TODO Auto-generated method stub
			mIsScanQRCodeOut = false;
			mScanCodeErrorLayout.setVisibility(View.VISIBLE);
		}
	};
	

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		UIBottomButtonsHelper.CURRENT_SCREEN_OF_4_MAINSCREEN = UIBottomButtonsHelper.SCAN_SCREEN;
		super.onBackPressed();
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		DataHelper.getInstance().deleteObserver(_me);
		super.onDestroy();
		if(thread!=null)
			thread.interrupt();
	}
	
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		if (data == null)
		{
			hideProcessDialog();
			mScanCodeErrorLayout.setVisibility(View.VISIBLE);
			return;
		}
		DataResult result = (DataResult) data;
		switch (result.getMethodName()) {
		case postQRCodeIn:
			hideProcessDialog();
			if (result.getErrorCode() == null) {
				if(result.getData().equals("Success")){
					getTextViewHeader().setText(getString(R.string.input_data));
					getFrameLayoutMain().removeAllViews();
					getFrameLayoutMain().addView(mInputDataLayout);
				}
				else
				{
					mScanCodeErrorLayout.setVisibility(View.VISIBLE);
					Util.showError(InputDataActivity.this, getString(R.string.app_name), getString(R.string.post_fail));
				}
			}
			else
			{
				mScanCodeErrorLayout.setVisibility(View.VISIBLE);
				Util.showError(InputDataActivity.this, getString(R.string.app_name),
						result.getErrorCode().getErrorMessage());
			}
			break;
		case postQRCodeOut:
			hideProcessDialog();
			if (result.getErrorCode() == null) {
				if(result.getData().equals("Success")){
					Util.showAlertDialog(InputDataActivity.this, mPostQRCodeOutCallback, false, true, getString(R.string.app_name), getString(R.string.post_out_success), getString(R.string.OK), "");
				}else{
					mScanCodeErrorLayout.setVisibility(View.VISIBLE);
					Util.showError(InputDataActivity.this, getString(R.string.app_name), getString(R.string.post_fail));
				}
			}
			else
			{
				mScanCodeErrorLayout.setVisibility(View.VISIBLE);
				Util.showError(InputDataActivity.this, getString(R.string.app_name),
						result.getErrorCode().getErrorMessage());
			}
			break;
		default: break;
		}
	}
		
	AlertDialogInterface mPostQRCodeOutCallback = new AlertDialogInterface() {
		
		@Override
		public void onChooseYesCallback() {
			// TODO Auto-generated method stub
			_me.onHistoriesButtonClick(null);
		}
		
		@Override
		public void onChooseNoCallback() {
			// TODO Auto-generated method stub
		}
	};
	
	private void showProcessDialog() {
		if (_waitingDialog == null || !_waitingDialog.isShowing()) {
			_waitingDialog = new ProgressDialog(this);
			_waitingDialog.setMessage(getString(R.string.processing));
			_waitingDialog.setCancelable(false);
			_waitingDialog.show();
		}
	}

	private void hideProcessDialog() {
		if (_waitingDialog != null && _waitingDialog.isShowing()) {
			_waitingDialog.dismiss();
		}
	}
}
